import { md5 } from "md5.js"
//注意：应用信息需登录https://dev.10ss.net，完善个人信息并选择应用类型创建后获得
const host = 'open-api.10ss.net';
const clientId = '1044442249';        //自有型应用下的应用id
const machineCode = '4004693461'      //终端号
const clientSecret = 'bf476fecc7a791591305d76d306f7942';   //自有型应用下的应用密钥


/**
 * 获取当前的时间戳
 * @returns {number}
 */
var getTimestamp = function()
{
    return Math.round(new Date() / 1000);
};

const timestamp = getTimestamp();

/**
 * uuid4
 * @returns {string}
 */
var uuid4 = function()
{   var s = [];

    var hexDigits = "0123456789abcdef";
  
    for (var i = 0; i < 36; i++) {
  
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  
    }
  
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  
    s[8] = s[13] = s[18] = s[23] = "-";
  
    var uuid = s.join("").replace("-","");
  
    return uuid
};

/**
 * 获取签名
 * @param tmp
 * @returns {*}
 */
var getSign = function(tmp)
{

    return md5(clientId + tmp + clientSecret);
};

/**
 * 获取调用凭证access_token
 */
var getToken = function()
{   
    let path = '/oauth/oauth';
    wx.request({
        url: 'https://' + host + path,
        data:{
            client_id: clientId,
            grant_type: 'client_credentials',
            scope: 'all',
            timestamp: timestamp,
            id: uuid4(),
            sign: getSign(timestamp)
        },
        method:"POST",
        header: {
            "content-type": "application/x-www-form-urlencoded"
        },
        success: function (tokenRes) {
            console.log('success',tokenRes)
            //假设获取access_token成功，接口的返回体（res.data）是：{"error":0,"error_description":"success","body":{"access_token":"123","refresh_token":"456","machine_code":"1111","expires_in":2592000,"scope":"all"}}
            var data = tokenRes.data
            if (data.error != 0) {
                //获取access_token失败，查看data.error_description分析原因
                alert(data.error_description);
                return false;
            }
            try{
                wx.setStorageSync('access_token', data.body.access_token)
            }catch (e) {
              
                return false;
            }
        },fail:function(res){
            console.log('fail',res)
        }
    })
};

/**
 * 添加打印机API
 * @param machineCode
 * @param mSign
 * @returns {boolean}
 */
var addPrinter = function (machineCode, msign)
{   
    let path = '/printer/addprinter';
    checkToken()
    try {
        var token = wx.getStorageSync('access_token');
        if (token) {
            wx.request({
                url: 'https://' + host + path,
                data:{
                    client_id: clientId,
                    access_token: token,
                    machine_code: machineCode,//易联云终端号
                    msign: msign,//易联云密钥
                    timestamp: timestamp,
                    id: uuid4(),
                    sign: getSign(timestamp)
                },
                method:"POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (res) {
                    if(res.data.error == 0){
                        wx.showToast({
                            title: '添加成功',
                          })
                       
                    }else{
                        wx.showToast({
                            title: '添加失败,终端号或密钥错误',
                            icon:'none'
                          })
                    }
                },fail:function(res){
                    wx.showToast({
                        title: '添加失败,终端号或密钥错误',
                        icon:'none'
                      })
                }
            })
        }
    }catch (e) {
        alert(e.message);
        return false;
    }
};

//小票排版
var strA = '.';
var strB = '*';
var content = "<FS2><center>**#1 美团**</center></FS2>";
content += strA.repeat( 32);
content += "<FS2><center>--在线支付--</center></FS2>";
content += "<FS><center>张周兄弟烧烤</center></FS>";
content += "订单时间:2018-12-27 16:23\n";
content += "订单编号:40807050607030\n";
content += strB.repeat( 14) + "商品" + strB.repeat( 14);
content += "<table>";
content += "<tr><td>烤土豆(超级辣)</td><td>x3</td><td>5.96</td></tr>";
content += "<tr><td>烤豆干(超级辣)</td><td>x2</td><td>3.88</td></tr>";
content += "<tr><td>烤鸡翅(超级辣)</td><td>x3</td><td>17.96</td></tr>";
content += "<tr><td>烤排骨(香辣)</td><td>x3</td><td>12.44</td></tr>";
content += "<tr><td>烤韭菜(超级辣)</td><td>x3</td><td>8.96</td></tr>";
content += "</table>";
content += strA.repeat( 32);
content += "<QR>这是二维码内容</QR>";
content += "小计:￥82\n";
content += "折扣:￥４ \n";
content += strB.repeat(32);
content += "订单总价:￥78 \n";
content += "<FS2><center>**#1 完**</center></FS2>";

/**
 * 文本打印API
 * @param machineCode
 * @param originId 订单号要求32个字符内，只能是数字、大小写字母 
 * @param content
 * @returns {boolean}
 */
var toPrint = function(machineCode, originId, content)
{
    let path = '/print/index';
    checkToken()
    try {
        var token = wx.getStorageSync('access_token');
        if (token) {
            wx.request({
                url: 'https://' + host + path,
                data:{
                    client_id: clientId,
                    access_token: token,
                    machine_code: machineCode,
                    origin_id: originId,//用户订单号：要求32个字符内，只能是数字、大小写字母 
                    content: content,
                    timestamp: timestamp,
                    id: uuid4(),
                    sign: getSign(timestamp)
                },
                method:"POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (printApiRes) {
                    console.log(printApiRes.data);
                }
            })
        }
    }catch (e) {
        alert(e.message);
        return false;
    }
};

/**
 * 图形打印API
 * @param machineCode
 * @param originId
 * @param pictureUrl
 * @returns {boolean}
 */
var toPicturePrint = function(machineCode, originId, pictureUrl)
{
    let path = '/pictureprint/index';
    checkToken()
    try {
        var token = wx.getStorageSync('access_token');
        if (token) {
            wx.request({
                url: 'https://' + host + path,
                data:{
                    client_id: clientId,
                    access_token: token,
                    machine_code: machineCode,
                    origin_id: originId,
                    picture_url: pictureUrl,
                    timestamp: timestamp,
                    id: uuid4(),
                    sign: getSign(timestamp)
                },
                method:"POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (printApiRes) {
                    console.log('打印成功',printApiRes.data);
                },fail:function(res){
                    console.log('打印图片失败',res)
                }
            
            })
        }
    }catch (e) {
        alert(e.message);
        return false;
    }
};
var setSound = function(machineCode, voice)
{
    let path = '/printer/setsound';
    checkToken()
    try {
        var token = wx.getStorageSync('access_token');
        if (token) {
            wx.request({
                url: 'https://' + host + path,
                data:{
                    client_id: clientId,
                    access_token: token,
                    machine_code: machineCode,
                    response_type:'horn' ,//蜂鸣器:buzzer,喇叭:horn
                    voice:voice,
                    sign: getSign(timestamp),
                    id: uuid4(),
                    timestamp: timestamp,
                },
                method:"POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (printApiRes) {
                    console.log('设置声音成功',printApiRes.data);
                },fail:function(res){
                    console.log('设置声音失败',res)
                }
            
            })
        }
    }catch (e) {
        alert(e.message);
        return false;
    }
};
var checkToken = function(){
    var token = wx.getStorageSync('access_token');
    if(token){
        console.log('checkToken is true')
    }else{
        getToken()
        console.log('checkToken is null')
    }
};
var getState = function(){
    let path = '/printer/getprintstatus';
    checkToken()
    try {
        var token = wx.getStorageSync('access_token');
        if (token) {
            wx.request({
                url: 'https://' + host + path,
                data:{
                    client_id: clientId,
                    access_token: token,
                    machine_code: machineCode,
                    sign: getSign(timestamp),
                    id: uuid4(),
                    timestamp: timestamp,
                },
                method:"POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (res) {
                    let state = parseInt(res.data.body.state)
                    getStateDesc(state)
                    // console.log('查询状态成功',state);
                },fail:function(res){
                    console.log('查询状态失败',res)
                }
            
            })
        }
    }catch (e) {
        alert(e.message);
        return false;
    }
};
var getStateDesc = function(number){
    switch(number){
        case 0:
            console.log('离线')
            break;
        case 1:
            console.log('在线')
            break;
        case 2:
            console.log('缺纸')
            break;
        default:
            console.log('未知异常')
            break;
    }
}
//执行步骤
//(1) getToken(); 调用一次即可，需替换缓存中token时再调用1次，记得每次调用都会替换缓存中的token每日上限20次，超出需要等待24小时才能重置次数
//(2) 未添加的打印机需要调用addPrinter('终端号', '终端密钥');
//(3) toPrint('终端号', '自定义订单id', '打印内容')
// getToken();
// toPrint('终端号', '自定义订单id', content);
module.exports={
    toPicturePrint,
    toPrint,
    addPrinter,
    getToken,
    getSign,
    uuid4,
    getTimestamp,
    setSound,
    getState,

}
